var query = require('../../common').Query;
var cacheUser = require('../../common').RefreshCache;
var map = require('../../common').Mapping;
var md5 = require('../../common').md5;
var _ = require("underscore");
var multiparty = require('multiparty');
var xlsx = require('node-xlsx');
var logger = require('../../common').logger;
var fs = require("fs");

var DEFAULT_PWD = md5('iflytek');

exports.findMemberPage = function (req, res) {
    res.render("findMemberTpl", map.generateNavBar(req));
};

exports.findMembers = function (req, res) {
    if (req.body.manager) {
        var found = false;
        for (var i in map.userName) {
            if (map.userName[i] === req.body.manager) {
                found = true;
                req.body.leader = parseInt(i);
            }
        }
        if (!found) {
            req.body.leader = 'null';
        }
    }
    query(map.sql.findMemberList, res, req.body, function (rows) {
        if (rows.data) {
            rows.data.forEach(function (e, i) {
                rows.data[i] = _.omit(e, 'pwd');
            });
        } else {
            rows.forEach(function (e, i) {
                rows[i] = _.omit(e, 'pwd');
            });
        }
        res.send(rows);
    });
};

exports.deleteMembers = function (req, res) {
    query(map.sql.memberBatchDelete, res, req.body, function (rows) {
        if (rows.affectedRows != 0) {
            res.send("success");
            cacheUser();
        } else {
            res.send({error: 503, description: map.error[503]});
        }
    });
};

exports.addMemberPage = function (req, res) {
    var obj = map.generateNavBar(req);
    obj.member = {u_id: '', u_name: '新用户', username: '', role: 'member', manager: ''};
    obj.list = {};
    res.render("editMemberTpl", obj);
};

exports.singleAddMemberPage = function (req, res) {
    var obj = map.generateNavBar(req);
    obj.member = {u_id: '', u_name: '新用户', username: '', role: 'member', manager: ''};
    res.render("editMemberTpl", obj);
};

exports.addMember = function (req, res) {
    if (req.body instanceof Array) {
        var i = 0;

        (function queryR() {
            if (i < req.body.length) {
                if (!req.body[i].pwd) {
                    req.body[i].pwd = DEFAULT_PWD;
                } else {
                    req.body[i].pwd = md5(req.body[i].pwd + "");
                }
                if (req.body[i].manager) {
                    query(map.sql.insertMember, res, req.body[i++], function () {
                    });
                } else {
                    query(map.sql.insertMemberNoManager, res, req.body[i++], function () {
                    });
                }
                queryR();
            } else {
                cacheUser();
                res.send('success');
            }
        })();
    } else {
        if (!req.body.pwd) {
            req.body.pwd = DEFAULT_PWD;
        } else {
            req.body.pwd = md5(req.body.pwd + "");
        }
        if (req.body.manager) {
            query(map.sql.insertMember, res, req.body, function () {
                cacheUser();
                res.send('success');
            });
        } else {
            query(map.sql.insertMemberNoManager, res, req.body, function () {
                cacheUser();
                res.send('success');
            });
        }
    }
};

exports.editMemberPage = function (req, res) {
    if (map.userRole[req.params.id] === 'admin') {
        res.cookie('toast', map.error[504], {path: '/member'});
        res.redirect("/member/find");
        return;
    }
    query(map.sql.findMemberList, res, {id: req.params.id}, function (rows) {
        if (rows.length == 1) {
            var obj = map.generateNavBar(req);
            rows[0].manager = map.userName[rows[0].manager];
            obj.member = rows[0];
            res.render("editMemberTpl", obj);
        } else {
            res.render('errorTpl', {code: 503, description: map.error[503]})
        }
    });
};

exports.saveMembers = function (req, res) {
    if (req.body.pwd) {
        req.body.pwd = md5(req.body.pwd + "");
    }
    query(map.sql.updateMember, res, req.body, function (rows) {
        if (rows.affectedRows != 0) {
            cacheUser();
            res.send("success");
        } else {
            res.send({error: 503, description: map.error[503]});
        }
    });
};

exports.uploadForm = function (req, res) {
    function dataComplete(object) {
        var valid = true;
        if (object.length < 3) {
            return false;
        }
        for (var i = 0; i < 3; i++) {
            if (!object[i] || (object[i].trim && object[i].trim().length == 0)) {
                valid = false;
            }
        }
        return valid;
    }

    var form = new multiparty.Form({uploadDir: './app/temp/'});
    form.parse(req, function (err, fields, files) {
        if (err) {
            console.log('parse error: ' + err);
            res.send(map.error[503]);
        } else {
            var tempFile = files['file'][0];
            logger.info("Upload File : " + tempFile.originalFilename);

            var obj = xlsx.parse(tempFile.path);
            fs.unlink(tempFile.path);

            var insertArray = [], project = null;
            var userR = {}, userNameR = {};
            query("SELECT u_name,username FROM user", res, {}, function (data) {
                data.forEach(function (ele) {
                    userR[ele.u_name] = true;
                    userNameR[ele.username] = true;
                });
                if (obj[0] && obj[0].data && obj[0].data.length > 0) {
                    //step1 : validate all data and push to array.
                    for (var i = 2; i < obj[0].data.length; i++) {
                        project = obj[0].data[i];
                        if (!!project[0]) {
                            if (!dataComplete(project)) {
                                res.send(map.error[506]);
                                return;
                            }
                            //user map reverse, p_status reverse, date. insert. query all project->map, unique check
                            if (!(project[1] in userR) && !(project[0] in userNameR)) {
                                if(/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/.test(project[2])) {
                                    insertArray.push({
                                        username: project[0],
                                        u_name: project[1],
                                        email: project[2],
                                        role: "member",
                                        pwd : DEFAULT_PWD 
                                    })
                                } else {
                                    res.send(map.error[506]);
                                    return;
                                }
                            } else {
                                res.send(map.error[507]);
                                return;
                            }
                        } else {
                            if (i == 2) {
                                res.send(map.error[505]);
                            } else {
                                break;
                            }
                        }
                    }

                    //step2 : insert all members in excel
                    var cursor = 0;
                    (function queryR() {
                        if (cursor < insertArray.length) {
                            query(map.sql.insertMemberNoManager, res, insertArray[cursor++], function () {
                            });
                            queryR();
                        } else {
                            res.send('success');
                        }
                    })();
                }
            });
        }
    });
};